package com.chineseall.app.scheduler;

import java.util.Map;
import java.util.Set;

import javax.websocket.CloseReason;
import javax.websocket.Session;

import jmind.core.support.LogUtil;

import org.springframework.stereotype.Component;

import com.chineseall.app.ConnectionManager;
import com.chineseall.app.ws.WebSocketEndpoint;

@Component("nbScheduler")
public class AppScheduler {

    public void zero() {

    }

    public void minute() {
        LogUtil.debug("Schedule stats={}", ConnectionManager.INSTANCE.stats());

        LogUtil.debug("free={},max={},total={},cpu={}", Runtime.getRuntime().freeMemory(), Runtime.getRuntime()
                .maxMemory(), Runtime.getRuntime().totalMemory(), Runtime.getRuntime().availableProcessors());
        //  if (Const.IS_PRODUCTION)
        cleanInvalid();
    }

    private void cleanInvalid() {
        Set<Session> sessions = ConnectionManager.INSTANCE.getOpenSessions();
        LogUtil.debug("open session=" + sessions.size());
        for (Session s : sessions) {
            Map<String, Object> map = s.getUserProperties();
            Integer uid = (Integer) map.get("uid");
            if (uid == null) {
                Long time = (Long) map.get("openTime");
                if (System.currentTimeMillis() - time > 60000) {
                    LogUtil.log.warn(s.isOpen() + "cleanInvalid1 sid={},map={}", s.getId(), s.getUserProperties());
                    ConnectionManager.INSTANCE.close(s, new CloseReason(CloseReason.CloseCodes.NO_STATUS_CODE,
                            "uid is null"));
                }

                continue;
            }
            WebSocketEndpoint ws = ConnectionManager.INSTANCE.getSession(uid);
            if (ws == null) {
                LogUtil.log.warn(s.isOpen() + "cleanInvalid2 sid={},map={}", s.getId(), s.getUserProperties());
                ConnectionManager.INSTANCE.close(s,
                        new CloseReason(CloseReason.CloseCodes.NO_STATUS_CODE, "ws is null"));

                continue;
            }

            if (!s.equals(ws.session)) {
                LogUtil.log.warn(s.isOpen() + "cleanInvalid3 sid={},map={}, ws={}", s.getId(), s.getUserProperties(),
                        ws);
                ConnectionManager.INSTANCE.close(s, new CloseReason(CloseReason.CloseCodes.NO_STATUS_CODE,
                        "session is repeat"));

                continue;
            }
        }
    }

}
